package com.bsh.serviceImpl;

import java.math.BigDecimal;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bsh.mybatis.model.Account;
import com.bsh.mybatis.model.AccountNotice;
import com.bsh.mybatis.model.AccountRefundWithBLOBs;
import com.bsh.repository.DaoAccount;
import com.bsh.repository.DaoAccountLog;
import com.bsh.repository.DaoAccountNotice;
import com.bsh.repository.DaoAccountRefund;
import com.bsh.repository.DaoUser;
import com.bsh.service.FinanceService;
import com.bsh.utils.system.AccountLock;

@Service
@Transactional
public class FinanceServiceImpl implements FinanceService {

	@Autowired
	DaoAccountRefund daoAccountRefund;
	@Autowired
	DaoAccountLog daoAccLog;
	@Autowired
	DaoAccount daoAcc;
	@Autowired
	DaoAccountNotice daoNotice;
	@Autowired
	DaoUser daoUser;
	
	@Override
	public Integer saveAccRef(Integer accountId ,Integer userid, Integer userBankId, Integer money, String memo) {
		AccountRefundWithBLOBs  ar=new AccountRefundWithBLOBs();
		ar.setAccountId(accountId);
		ar.setMoney(new BigDecimal(money));
		ar.setUserid(userid);
		ar.setUserBankId(userBankId);
		ar.setMemo(memo);
		ar.setAuditStatus((short)0);
		ar.setIsPay((short)0);
		ar.setCreateTime(new Date());
		return daoAccountRefund.insert(ar);
	}

	@Override
	public Integer withdrawalMoney(Integer accountId, int userid, String sn, String ip,int withdrawalMoney,String bankCard, String bankName, String memo) {
		Integer res=-1;
		//添加账务锁
		boolean isLock = AccountLock.getLock(accountId, userid);
		if (!isLock) {
			res=-11;
			return res;
		}
		// 账户变动前记录日志
	    daoAccLog.addLog(accountId, sn, ip);
		// 扣余额
		daoAcc.addMoney(accountId, userid, BigDecimal.ZERO.subtract(new BigDecimal(withdrawalMoney)));
		// 读取用户账户信息
		Account  endAccInfo=daoAcc.getUserAccount(userid);
		// 写商币日志明细
		AccountNotice notice = new AccountNotice();
		notice.setAccountId(accountId);//账户id
		notice.setUserid(userid);//用户id
		notice.setMoney(BigDecimal.ZERO.subtract(new BigDecimal(withdrawalMoney)));//充值为正，提款为负
		notice.setTradeType(3); // 用户提现
		notice.setSn(sn);// 流水号
		notice.setOuterTime(new Date());
		notice.setOperator(userid);// 操作人
		notice.setTitle("用户提现："+new BigDecimal(withdrawalMoney)+"元");
		notice.setMemo(memo);
		notice.setPaymentId(2);// 用户操作类型
		notice.setIp(ip);
		notice.setIsPaid((byte) 1);// 已付款
		notice.setMoneyType((short) 1);// 现金类型
		notice.setBankCard(bankCard);
		notice.setBankName(bankName);
		notice.setCreateTime(new Date());
		notice.setMoneyDown(endAccInfo.getMoney()); // 结存现金余额
		notice.setCloudMoneyDown(endAccInfo.getCloudMoney()); // 结存商币余额
		res=daoNotice.insert(notice);
		//释放锁
		AccountLock.unLock(accountId, userid);
		
		return res;
	}

}
